import React, { useEffect, useRef, useState } from 'react'
import { TabBar, Header, ComputeTime, Loading, RouterView } from 'src/components'
import { CSSTransition } from "react-transition-group";
import { getOrderList } from 'src/api/getData'
import { imgBaseUrl } from 'src/config/env'
import { SAVE_ORDER } from 'src/redux/action-type'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory, Link } from 'react-router-dom'
import InfiniteScroll from "react-infinite-scroller";
import routerData from './routerData';
import './index.scss'

const Order = () => {
    const dispatch = useDispatch()
    const history = useHistory()
    const { userInfo, geohash } = useSelector(state => state);
    const [orderList, setOrderList] = useState() //订单列表
    const [offset, setOffset] = useState(0)
    const [preventRepeat, setPreventRepeat] = useState(false)  //防止重复获取
    const [showLoading, setShowLoading] = useState(true) //显示加载动画
    const scrollParentRef = useRef()



    useEffect(() => {
        //初始化获取信息
        const initData = async () => {
            if (userInfo && userInfo.user_id) {
                let res = await getOrderList(userInfo.user_id, offset);
                setOrderList([...res])
                setShowLoading(false)
            } else {
                setShowLoading(false)
            }
        }
        initData()
    }, [userInfo, offset])

    //加载更多
    const loaderMore = async () => {
        if (preventRepeat) {
            return
        }
        setPreventRepeat(true)
        setShowLoading(true)
        setOffset(offset + 10)

        //获取信息
        let res = await getOrderList(userInfo.user_id, offset);
        setOrderList([...orderList, ...res])
        setShowLoading(false)
        if (res.length < 10) {
            return
        }
        setPreventRepeat(false)
    }

    //显示详情页
    const showDetail = (item) => {
        dispatch({
            type: SAVE_ORDER,
            item
        })
        setPreventRepeat(false)
        history.push('/order/detail');
    }

    return <div className="page_order">
        <Header title="订单列表" goBack></Header>
        <div ref={scrollParentRef}>
            <InfiniteScroll
                initialLoad={false}
                pageStart={1}
                loadMore={loaderMore}
                hasMore={true}
                useWindow={false}
                getScrollParent={() => scrollParentRef.current}
            >
                <ul className="order_list_ul">
                    {
                        orderList && orderList.map((item) => {
                            return <li className="order_list_li" key={item.id}>
                                <img src={imgBaseUrl + item.restaurant_image_url} className="restaurant_image" alt="" />
                                <section className="order_item_right">
                                    <section onClick={() => showDetail(item)}>
                                        <header className="order_item_right_header">
                                            <section className="order_header">
                                                <h4 >
                                                    <span className="ellipsis">{item.restaurant_name} </span>
                                                    <svg fill="#333" className="arrow_right">
                                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
                                                    </svg>
                                                </h4>
                                                <p className="order_time">{item.formatted_created_at}</p>
                                            </section>
                                            <p className="order_status">
                                                {item.status_bar.title}
                                            </p>
                                        </header>
                                        <section className="order_basket">
                                            <p className="order_name ellipsis">{item.basket.group[0][0].name}{item.basket.group[0].length > 1 ? ' 等' + item.basket.group[0].length + '件商品' : ''}</p>
                                            <p className="order_amount">¥{item.total_amount.toFixed(2)}</p>
                                        </section>
                                    </section>
                                    <div className="order_again">
                                        {
                                            item.status_bar.title === '等待支付' ?
                                                <ComputeTime time={item.time_pass}></ComputeTime>
                                                :
                                                <span className="buy_again">
                                                    <Link to={`/shop?geohash=${geohash}&id=${item.restaurant_id}`} >再来一单</Link>
                                                </span>
                                        }
                                    </div>
                                </section>
                            </li>
                        })
                    }
                </ul>
            </InfiniteScroll>
        </div>
        <TabBar />
        <CSSTransition classNames="loading" in={showLoading} timeout={500} unmountOnExit>
            <Loading />
        </CSSTransition>
        <RouterView data={routerData} />
    </div>
}

export default Order